package com.swj.auth.service.impl;

import com.swj.auth.service.ISysLoginService;
import com.swj.auth.service.ISysPasswordService;
import com.swj.auth.service.ISysRecordLogService;
import com.swj.common.core.constant.Constants;
import com.swj.common.core.constant.SecurityConstants;
import com.swj.common.core.constant.UserConstants;
import com.swj.common.core.enums.UserStatus;
import com.swj.common.core.exception.auth.AuthException;
import com.swj.common.core.exception.user.UserLoginFailException;
import com.swj.common.core.model.SysUser;
import com.swj.common.core.model.vo.LogInVo;
import com.swj.common.core.model.vo.LoginUserVo;
import com.swj.common.core.model.web.RestResult;
import com.swj.common.core.remoteService.RemoteUserService;
import com.swj.common.core.utils.ResponseUtil;
import com.swj.common.core.utils.SysStringUtil;
import com.swj.common.core.utils.ip.IpUtils;
import com.swj.common.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * 登录处理服务层
 *
 * @author 10834
 */
@Service
@Slf4j
public class SysLoginServiceImpl implements ISysLoginService {
    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private ISysPasswordService passwordService;

    @Autowired
    private ISysRecordLogService recordLogService;

    @Override
    public LoginUserVo logIn(LogInVo logInVo) {

        //初步校验密码和用户名有误错误
        this.checkUserNameAndPassword(logInVo.getUserName(), logInVo.getPassword());
        // 查询用户信息
        RestResult<LoginUserVo> userResult = remoteUserService.getUserInfo(logInVo.getUserName(), SecurityConstants.INNER);

        if (Objects.equals(userResult.getCode(), ResponseUtil.ERROR_CODE)) {
            log.info("登录失败,服务器内部错误!");
            recordLogService.recordLogininfor(logInVo.getUserName(), Constants.LOGIN_FAIL, "登录失败,服务器内部错误:" + userResult.getError());
            throw new UserLoginFailException("登录失败,服务器内部错误:" + userResult.getError());
        }

        if (SysStringUtil.isNull(userResult) || SysStringUtil.isNull(userResult.getData())) {
            log.info("登录用户：" + logInVo.getUserName() + " 不存在");
            recordLogService.recordLogininfor(logInVo.getUserName(), Constants.LOGIN_FAIL, "登录用户不存在");
            throw new UserLoginFailException("登录用户：" + logInVo.getUserName() + " 不存在");
        }

        if (Objects.equals(ResponseUtil.ERROR_CODE, userResult.getCode())) {
            log.info("登录失败,登录用户不存在:{}", userResult.getMsg());
            recordLogService.recordLogininfor(logInVo.getUserName(), Constants.LOGIN_FAIL, "登录用户不存在");
            throw new UserLoginFailException(userResult.getMsg());
        }

        LoginUserVo userInfo = userResult.getData();

        SysUser user = userInfo.getSysUser();
        if (UserStatus.DELETED.getCode().equals(user.getDeleteStatus())) {
            log.info("对不起，您的账号：" + logInVo.getUserName() + " 已被删除");
            recordLogService.recordLogininfor(logInVo.getUserName(), Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new UserLoginFailException("对不起，您的账号：" + logInVo.getUserName() + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("对不起，您的账号：" + logInVo.getUserName() + " 已停用");
            recordLogService.recordLogininfor(logInVo.getUserName(), Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new UserLoginFailException("对不起，您的账号：" + logInVo.getUserName() + " 已停用");
        }
        passwordService.validate(user, logInVo.getPassword());
        recordLogIn(user);
        recordLogService.recordLogininfor(logInVo.getUserName(), Constants.LOGIN_SUCCESS, "登录成功");
        return userInfo;
    }

    private void checkUserNameAndPassword(String username, String password) {

        // 用户名或密码为空 错误
        if (SysStringUtil.isAnyBlank(username, password)) {
            log.info("用户名/密码必须填写");
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户名/密码必须填写");
            throw new UserLoginFailException("用户名/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            log.info("用户密码不在指定范围");
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户密码不在指定范围");
            throw new UserLoginFailException("用户密码不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            log.info("用户名不在指定范围");
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户名不在指定范围");
            throw new UserLoginFailException("用户名不在指定范围");
        }
    }

    /**
     * @param sysUser 用户实体
     */
    @Override
    public void register(SysUser sysUser) {

        String userName = sysUser.getUserName();
        String password = sysUser.getPassword();
        // 用户名或密码为空 错误
        if (SysStringUtil.isAnyBlank(userName, password)) {
            throw new AuthException("用户/密码必须填写");
        }
        if (userName.length() < UserConstants.USERNAME_MIN_LENGTH || userName.length() > UserConstants.USERNAME_MAX_LENGTH) {
            throw new AuthException("账户长度必须在2到20个字符之间");
        }
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            throw new AuthException("密码长度必须在5到20个字符之间");
        }

        // 注册用户信息
        if (SysStringUtil.isBlank(sysUser.getNickName())) {
            sysUser.setNickName(userName);
        }
        sysUser.setPassword(SecurityUtil.encryptPassword(password));
        RestResult<Boolean> registerResult = remoteUserService.registerUserInfo(sysUser, SecurityConstants.INNER);
        if (ResponseUtil.ERROR_CODE.equals(registerResult.getCode())) {
            throw new AuthException(registerResult.getMsg());
        }
        recordLogService.recordLogininfor(userName, Constants.REGISTER, "注册成功");
    }

    /**
     * 更新用户登录信息
     *
     * @param user yh
     */
    @Override
    public void recordLogIn(SysUser user) {
        String ip = IpUtils.getIpAddr();
        user.setLoginIp(ip);
        user.setLoginTime(LocalDateTime.now());
        if (SysStringUtil.isNotEmpty(user.getLoginedIp())) {
            Set<String> loginIp = new HashSet<>(List.of(user.getLoginedIp().split(",")));
            loginIp.add(ip);
            user.setLoginedIp(String.join(",", loginIp));
        } else {
            user.setLoginedIp(ip);
        }
        remoteUserService.recordlogin(user, SecurityConstants.INNER);
    }

    /**
     * 用户登出
     *
     * @param loginName 登出的用户名
     */
    @Override
    public void logout(String loginName) {
        recordLogService.recordLogininfor(loginName, Constants.LOGOUT, "退出成功");
    }
}
